package boddaert.philippe.cashGame.merge;

import java.util.HashMap;
import java.util.List;

import boddaert.philippe.cashGame.Game;
import boddaert.philippe.cashGame.GameConfiguration;

public class FastMerger {

	public static HashMap<String, Game> merge(List<Game>... lists) {
		if (lists == null)
			throw new IllegalArgumentException();
		HashMap<String, Game> mergedList = new HashMap<String, Game>();

		for (List<Game> list : lists) {
			if (list != null) {
				for (Game game : list) {
					String upperCaseTitleGame = game.getTitle().toUpperCase();
					if (!mergedList.containsKey(upperCaseTitleGame)) {
						addNewGameWithoutConfiguration(mergedList, game,
								upperCaseTitleGame);
					}
					addConfigurationToGame(mergedList.get(upperCaseTitleGame),
							game.getConfigurations());
				}
			}
		}
		return mergedList;
	}

	private static void addConfigurationToGame(Game game,
			List<GameConfiguration> configurations) {
		GameConfiguration configurationExisting;
		for (GameConfiguration configuration : configurations) {
			configurationExisting = game.getConfiguration(configuration
					.getSite());
			if (configurationExisting == null)
				game.addConfiguration(configuration);
			else {
				mergeConfiguration(configurationExisting, configuration);
			}
		}
	}

	private static void mergeConfiguration(
			GameConfiguration configurationExisting,
			GameConfiguration newConfiguration) {

		if (newConfiguration.getBestPrice() < configurationExisting
				.getBestPrice()) {
			configurationExisting.setBestPrice(newConfiguration.getBestPrice());
			configurationExisting.setNumberNewAvailable(configurationExisting
					.getNumberNewAvailable()
					+ newConfiguration.getNumberNewAvailable());
			configurationExisting
					.setNumberSecondHandAvailable(configurationExisting
							.getNumberSecondHandAvailable()
							+ newConfiguration.getNumberSecondHandAvailable());
			configurationExisting.setUrl(newConfiguration.getUrl());
		}
	}

	private static void addNewGameWithoutConfiguration(
			HashMap<String, Game> mergedList, Game game,
			String upperCaseTitleGame) {
		Game gameWithoutConfiguration = new Game();
		gameWithoutConfiguration.setTitle(game.getTitle());
		mergedList.put(upperCaseTitleGame, gameWithoutConfiguration);
	}

}
